# -*- coding: utf-8 -*-

import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '12384': {  # 易宝支付 拼多多3.8% 100-5000 dwc
        'API_KEY': 'nYvH5ST1cIoltpxfqawhVM3ske9iPbg6',
        'gateway': 'https://www.875628.com/api/create_order',
        'query_gateway': 'https://www.875628.com/api/query_order',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] and k != 'sign_type':
            s += '%s=%s&' % (k, parameter[k])
    s += '%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yibaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay_web':
        return 'alipay.web'
    elif service == 'alipay_wap':
        return 'alipay.wap'
    elif service == 'wechat_scan':
        return 'wechat.native'
    elif service == 'wechat_h5':
        return 'wechat.h5'
    elif service == 'unionpay':
        return 'unionpay.quick'
    return 'alipay.wap'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('format', 'html'),
        # ('format', 'json'),
        ('mch_id', str(app_id)),
        ('out_trade_no', str(pay.id)),
        ('pay_type', str(_get_pay_type(service))),
        ('total_fee', '%.2f' % pay_amount),
        ('return_url', '{}/pay/api/{}/yibaopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notify_url', '{}/pay/api/{}/yibaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yibaopay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    # headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    # response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5, verify=False)
    # _LOGGER.info("yibaopay create rsp: %s", response.text)
    # return {'charge_info': json.loads(response.text)['data']['url']}

    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('yibaopay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("yibaopay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yibaopay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yibaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = str(data['trade_no'])
    total_fee = float(data['pay_money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 1成功；0失败
    if trade_status == '1':
        _LOGGER.info('yibaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('sign_type', 'MD5'),
        ('mch_id', app_id),
        ('out_trade_no', str(pay_order.id)),
        ('timestamp', local_now().strftime("%Y-%m-%d %H:%M:%S")),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('yibaopay query data: %s, order_id is: %s', json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5, verify=False)
    _LOGGER.info('yibaopay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['pay_money'])
        trade_no = str(pay_order.third_id)
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 1支付，0未支付
        if trade_status == '1':
            _LOGGER.info('yibaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
